package com.zt.rongda.stock.controller;

import com.zt.servlet.*;
import com.zt.rongda.stock.model.StockType;
import com.zt.rongda.stock.service.StockTypeService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Controller
@RequestMapping(value = "/stockType")
public class StockTypeController {

    @Autowired
    private StockTypeService stockTypeService;

    @RequestMapping(value = "/query")
    @ResponseBody
    public JSONObject query(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        return Response.response(stockTypeService.getTable(reqBean));
    }

    @RequestMapping(value = "/queryById")
    @ResponseBody
    public JSONObject queryById(@RequestAttribute(ReqBean.NAME) String typeId) {
        return Response.response(stockTypeService.getById(typeId));
    }

    @RequestMapping(value = "/tree")
    @ResponseBody
    public JSONObject queryTree(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        return Response.response(stockTypeService.queryTree());
    }

    @RequestMapping(value = "/stockTree")
    @ResponseBody
    public JSONObject stockTree(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        return Response.response(stockTypeService.stockTree());
    }

    @RequestMapping(value = "/add")
    @ResponseBody
    public JSONObject add(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        stockTypeService.add(getStockType(reqBean));
        return Response.responseSuccess();
    }

    @RequestMapping(value = "/update")
    @ResponseBody
    public JSONObject update(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        stockTypeService.update(getStockType(reqBean));
        return Response.responseSuccess();
    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    public JSONObject delete(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        stockTypeService.delete(reqBean.getInfo("typeId"));
        return Response.responseSuccess();
    }

    /**
    * 从表单获取对象
    *
    * @param reqBean
    * @return
    */
    private StockType getStockType(ReqBean reqBean) {
        StockType stockType = new StockType();
        stockType.setTypeId(reqBean.getInfo("typeId"));
        stockType.setTypeName(reqBean.getInfo("typeName"));
        stockType.setParentTypeId(reqBean.getInfo("parentTypeId"));
        stockType.setUnit(reqBean.getInfo("unit"));
        stockType.setAlertNum( (reqBean.getInfo("alertNum") == "" || reqBean.getInfo("alertNum") == null ) ? null : reqBean.getInfoInt("alertNum"));
        return stockType;
    }

}